<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="ruleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc" label-width="140px">
        <el-input v-model="ruleForm.roleDesc"></el-input>
      </el-form-item>

      <el-form-item label="角色状态" prop="roleStatus">
        <el-radio-group v-model="ruleForm.roleStatus">
          <el-radio label="1">启用</el-radio>
          <el-radio label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即创建</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  mounted: function () {
    //判断有无传值，有传值则修改需要提前查询并填充数据，无传值则添加
    if (this.$route.params.id != null) {
      this.selectRoleById();
    }
  },

  data() {
    return {
      ruleForm: {
          id:"",
        roleName: "",
        roleDesc: "",
        roleStatus: "",
      },
      rules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        roleDesc: [
          { required: true, message: "请输入角色描述信息", trigger: "change" },
        ],
        roleStatus: [
          {
            required: true,
            message: "请至少选择一个角色状态",
            trigger: "change",
          },
        ],
      },
    
    };
  },

  methods: {
    //通过动态路由传入的id来进行查询并提前填充数据
    selectRoleById() {
      this.$httpRequest
        .get("role/selectRoleById", {
          params: { id: this.$route.params.id },
        })
        .then(({ data }) => {
          this.ruleForm = data.data;
            this.ruleForm.roleStatus=data.data.roleStatus+"";
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //用户点击提交后根据动态路由是否有传值进行分别处理
    submitForm(formName) {
      var url;
      if (this.$route.params.id != null) {
        url = "role/updateRole";
      } else {
        url = "role/addRole";
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var app = this;
          this.$httpRequest
            .post(url, {
              id: this.ruleForm.id,
              roleName: this.ruleForm.roleName,
              roleDesc: this.ruleForm.roleDesc,
              roleStatus: this.ruleForm.roleStatus,
            })
            .then(({ data }) => {
              console.log(data);
              app.$router.push("/toRoleList");
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
</style>